package cn.pli.bike.model.http;

import com.framemodule.utils.CommonUtils;
import com.framemodule.utils.Logger;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.lang.reflect.Type;

import cn.pli.bike.ui.CommonConstant;
import okhttp3.ResponseBody;
import retrofit2.Converter;

/**
 * Created by Charles on 2016/3/17.
 */
class GsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
    private final Gson gson;
    private final Type type;

    GsonResponseBodyConverter(Gson gson, Type type) {
        this.gson = gson;
        this.type = type;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {
        String response = value.string();
        try {
            Logger.d("url:response" + response);
            //ResultResponse 只解析result字段
            JSONObject jsonObject = null;
            int code = 0;
            try {
                jsonObject = new JSONObject(response);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            code = jsonObject.optInt("code");
            if (code != CommonConstant.CODE_SUCCESS) {
                if (CommonUtils.isNotEmpty(jsonObject.optString("msg"))) {
                    throw new ApiException(code, jsonObject.optString("msg"));
                } else {
                    throw new ApiException(code, "");
                }
            }
            return gson.fromJson(response, type);
        } finally {
        }
    }
}
